package com.zjeav.lingjiao.ui.home;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.dalimao.corelibrary.utils.FileUtil;
import com.google.gson.JsonObject;
import com.jpeng.jptabbar.JPTabBar;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import com.zjeav.lingjiao.BuildConfig;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.baseBean.Account;
import com.zjeav.lingjiao.base.baseBean.BaseApplication;
import com.zjeav.lingjiao.base.baseBean.Result;
import com.zjeav.lingjiao.base.baseBean.UploadSuccess;
import com.zjeav.lingjiao.base.config.BaseConfig;
import com.zjeav.lingjiao.base.listener.HttpCallbackListener;
import com.zjeav.lingjiao.base.tools.SharedPreferencesUtils;
import com.zjeav.lingjiao.base.utils.UIUtils;
import com.zjeav.lingjiao.ui.book.H5Activity;
import com.zjeav.lingjiao.ui.book.SaoMiaoBookActivity;
import com.zjeav.lingjiao.ui.personCenter.ClipImageActivity;
import com.zjeav.lingjiao.ui.personCenter.MyCourseActivity;
import com.zjeav.lingjiao.ui.personCenter.MyDownLoadActivity;
import com.zjeav.lingjiao.ui.personCenter.MyFavoriteActivity;
import com.zjeav.lingjiao.ui.personCenter.OrderActivity;
import com.zjeav.lingjiao.ui.personCenter.PersonInfoActivity;
import com.zjeav.lingjiao.ui.personCenter.PersonPresenter;
import com.zjeav.lingjiao.ui.personCenter.SysSetActivity;
import com.zjeav.lingjiao.ui.personCenter.view.PersonInfoContract;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static android.app.Activity.RESULT_OK;
import static com.dalimao.corelibrary.utils.FileUtil.getRealFilePathFromUri;
import static com.zjeav.lingjiao.R2.attr.content;

/**
 * Created by jpeng on 16-11-14.
 */
public class MineFragment extends Fragment implements View.OnClickListener,
        HttpCallbackListener, PersonInfoContract.View {

    private ImageView header_img;
    private ImageView saomiao_img;
    private File fileupload;
    private int REQUEST_CODE_SCAN = 111;
    private TextView buy_rec_txt, my_collect_txt, my_download, my_course_txt, person_info_txt, sys_set_txt;
    private static RelativeLayout buy_rec_rl;
    private RelativeLayout my_collect_rl;
    private RelativeLayout my_download_rl;
    private RelativeLayout my_course_rl;
    private TextView userconnect;
    private RelativeLayout person_info_rl;
    private RelativeLayout sys_set_rl;
    Intent intent;
    private PersonPresenter personPresenter;
    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    //请求相册
    private static final int REQUEST_PICK = 101;
    //请求截图
    private static final int REQUEST_CROP_PHOTO = 102;
    //请求访问外部存储
    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;
    //请求写入外部存储
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 10000000; // 超时时间
    private static final String CHARSET = "utf-8"; // 设置编码
    //调用照相机返回图片文件
    private File tempFile;
    // 1: qq, 2: weixin
    private int type;
    private boolean mallmode;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.mine_layout, null);
        init(layout);
        return layout;
    }

    private void init(View layout) {
        personPresenter = new PersonPresenter(this);
        header_img = layout.findViewById(R.id.header_img);
        buy_rec_txt = layout.findViewById(R.id.buy_rec_txt);
        my_collect_txt = layout.findViewById(R.id.my_collect_txt);
        my_download = layout.findViewById(R.id.my_download);
        my_course_txt = layout.findViewById(R.id.my_course_txt);
        person_info_txt = layout.findViewById(R.id.person_info_txt);
        sys_set_txt = layout.findViewById(R.id.sys_set_txt);
        buy_rec_rl = layout.findViewById(R.id.buy_rec_rl);
        my_collect_rl = layout.findViewById(R.id.my_collect_rl);
        userconnect = layout.findViewById(R.id.userconnect);
        my_download_rl = layout.findViewById(R.id.my_download_rl);
        my_course_rl = layout.findViewById(R.id.my_course_rl);
        person_info_rl = layout.findViewById(R.id.person_info_rl);
        sys_set_rl = layout.findViewById(R.id.sys_set_rl);
        saomiao_img = layout.findViewById(R.id.saomiao_img);
        saomiao_img.setOnClickListener(this);
        header_img.setOnClickListener(this);
        buy_rec_rl.setOnClickListener(this);
        my_collect_rl.setOnClickListener(this);
        my_download_rl.setOnClickListener(this);
        my_course_rl.setOnClickListener(this);
        person_info_rl.setOnClickListener(this);
        sys_set_rl.setOnClickListener(this);
        userconnect.setOnClickListener(this);

        personPresenter.getAccount();
    }

    public static void setViewVisible(boolean isvisible) {
        if (buy_rec_rl == null) {
            return;
        }
        if (isvisible) {
            buy_rec_rl.setVisibility(View.VISIBLE);
        } else {
            buy_rec_rl.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buy_rec_rl: //购买记录
                intent = new Intent(getContext(), OrderActivity.class);
                startActivity(intent);
                break;
            case R.id.my_collect_rl: //我的收藏
                intent = new Intent(getContext(), MyFavoriteActivity.class);
                startActivity(intent);
                break;
            case R.id.my_download_rl: //我的下载
                intent = new Intent(getContext(), MyDownLoadActivity.class);
                startActivity(intent);
                break;
            case R.id.my_course_rl: //我的课程
                intent = new Intent(getContext(), MyCourseActivity.class);
                startActivity(intent);
                break;
            case R.id.person_info_rl: //个人信息
                intent = new Intent(getContext(), PersonInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.sys_set_rl: //系统设置
                intent = new Intent(getContext(), SysSetActivity.class);
                startActivity(intent);
                break;
            case R.id.tabbar:
                JPTabBar tabBar = (JPTabBar) ((Activity) getContext()).findViewById(R.id.tabbar);
                tabBar.setTabTypeFace("fonts/Jaden.ttf");
                break;
            case R.id.saomiao_img:
                saoMiao();
                break;
            case R.id.userconnect:
                intent = new Intent(getContext(), H5Activity.class);
                intent.putExtra("applyUrl","http://api.listenjoin.com/home/cantactus");
                startActivity(intent);
                break;
            case R.id.header_img:
                type = 1;
                uploadHeadImage();
                break;
            default:
                break;
        }
    }

    private void saoMiao() {
        Intent intent = new Intent(getActivity(), CaptureActivity.class);

        /*ZxingConfig是配置类
         *可以设置是否显示底部布局，闪光灯，相册，
         * 是否播放提示音  震动
         * 设置扫描框颜色等
         * 也可以不传这个参数
         * */
        ZxingConfig config = new ZxingConfig();
        config.setPlayBeep(true);//是否播放扫描声音 默认为true
        config.setShake(true);//是否震动  默认为true
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                Intent intent = new Intent(getContext(), SaoMiaoBookActivity.class);
                intent.putExtra("content", content);
                startActivity(intent);
            }
        }

        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == RESULT_OK) {
                    gotoClipActivity(Uri.fromFile(tempFile));
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    gotoClipActivity(uri);
                }
                break;
            case REQUEST_CROP_PHOTO:  //剪切图片返回
                if (resultCode == RESULT_OK) {
                    try {
                        final Uri uri = data.getData();
                        if (uri == null) {
                            return;
                        }
                        String cropImagePath = getRealFilePathFromUri(getActivity().getApplicationContext(), uri);
                        Bitmap bitMap = BitmapFactory.decodeFile(cropImagePath);

                        fileupload = new File(saveFile(bitMap));
                        if (fileupload.exists()) {

                            final String url = BaseConfig.API_SERVICE_URL + "common/uploadFile?type=1";
                            String fileName = fileupload.getAbsolutePath();
                            UploadThread thread = new UploadThread(fileName, url);
                            thread.start();

                            Glide.with(getActivity())
                                    .load(fileupload)
                                    .into(header_img);
                           /* new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    uploadFile(fileupload,url);
                                }
                            }).start();*/
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                break;
        }

    }


    /**
     * 把bitmap压缩成jpeg保存到本地
     *
     * @param bitmap
     * @return
     */
    public static String saveFile(Bitmap bitmap) {
        String filename = "";
        try {
            FileOutputStream fout = null;
            String pathname = Environment.getExternalStorageDirectory().getPath() + File.separator + "tianxinenterprise" + File.separator;
            File file = new File(pathname);
            file.mkdirs();
            filename = pathname + File.separator + System.currentTimeMillis() + ".jpg";

            File file1 = new File(filename);
            if (file1.exists()) {
                file1.delete();
            }

            file1.createNewFile();

            fout = new FileOutputStream(filename);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fout);
            fout.flush();
            fout.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }

    @Override
    public void onFinish(int response) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                UIUtils.showToast("头像更新成功");
            }
        });

    }

    @Override
    public void onError(Exception e) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //  UIUtils.showToast("更新失败");
            }
        });

    }

    @Override
    public void showPersonInfo(Account account) {
        String url = account.getAvator();
        Glide.with(getActivity())
                .load(url)
                .error(getResources().getDrawable(R.mipmap.avatar))
                .into(header_img);

    }

    @Override
    public void showUpdate(Result result, int type) {
        Toast.makeText(getActivity(), "头像上传成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showError(Throwable throwable) {
        Log.d("","");
    }

    /**
     * 上传头像
     */
    private void uploadHeadImage() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_popupwindow, null);
        TextView btnCarema = (TextView) view.findViewById(R.id.btn_camera);
        TextView btnPhoto = (TextView) view.findViewById(R.id.btn_photo);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        View parent = LayoutInflater.from(getActivity()).inflate(R.layout.activity_main, null);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();
        params.alpha = 0.5f;
        getActivity().getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getActivity().getWindow().setAttributes(params);
            }
        });

        btnCarema.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限判断
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到调用系统相机
                    gotoCamera();
                }
                popupWindow.dismiss();
            }
        });
        btnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限判断
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请READ_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            READ_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到相册
                    gotoPhoto();
                }
                popupWindow.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }


    /**
     * 外部存储权限申请返回
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                gotoCamera();
            }
        } else if (requestCode == READ_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                gotoPhoto();
            }
        }
    }


    /**
     * 跳转到相册
     */
    private void gotoPhoto() {
        Log.d("evan", "*****************打开图库********************");
        //跳转到调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }


    /**
     * 跳转到照相机
     */
    private void gotoCamera() {
        Log.d("evan", "*****************打开相机********************");
        //创建拍照存储的图片文件
        tempFile = new File(FileUtil.checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"), System.currentTimeMillis() + ".jpg");

        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //设置7.0中共享文件，分享路径定义在xml/file_paths.xml
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(getActivity(), "com.zjeav.lingjiao.fileprovider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(getActivity(), ClipImageActivity.class);
        intent.putExtra("type", type);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }


    public class UploadThread extends Thread {
        private String fileName;
        private String url;

        public UploadThread(String fileName, String url) {
            this.fileName = fileName;
            this.url = url;
        }

        @Override
        public void run() {
            uploadHttpClient();
//		httpUpload();
        }

        private void uploadHttpClient() {
            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(url);

                File parent = Environment.getExternalStorageDirectory();
                File filAbs = new File(parent, "image.jpg");

                MultipartEntity muti = new MultipartEntity();
                FileBody fileBody = new FileBody(fileupload);
                muti.addPart("file", fileBody);
                post.setEntity(muti);
                post.setHeader("authtoken", SharedPreferencesUtils.getParam(BaseApplication.getContext(), "authtoken", "").toString());

                HttpResponse response = client.execute(post);

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    String str = EntityUtils.toString(response.getEntity());
                    Log.i("meng", str);

                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(str);
                    com.alibaba.fastjson.JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                    String strurl = (String) jsonObject1.get("fileUrl");

                    Account account = new Account();
                    account.setAvator(strurl);
                    personPresenter.upPersonInfo(account, 0);

                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

        }

    }

}
